package com.ft.controller;

import com.ft.domain.Answer;
import com.ft.domain.StudyAnswer;
import com.ft.service.IAnswerService;
import com.ft.service.IStudyAnswerService;
import com.ft.utils.Code;
import com.ft.utils.Result;
import com.ft.utils.SnowFlakeGenerateIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.List;

/**
 * @Author: ft
 * @Date: 2023/01/12/18:05
 * @Description:
 */
@RestController
@CrossOrigin
@RequestMapping("/studyanswer")
public class StudyAnswerController {
    @Autowired
    private IStudyAnswerService answerService;
    /**
     * 创建回复评论
     * @param answer
     * @return
     */
    @PostMapping("/{num}")
    public Result addAnswer(@RequestBody StudyAnswer answer, @PathVariable String num) throws IllegalAccessException {
        //创建订单编号
        SnowFlakeGenerateIdWorker snowFlakeGenerateIdWorker =
                new SnowFlakeGenerateIdWorker(0L,0L);
        String id = snowFlakeGenerateIdWorker.generateNextId();
        //设置订单编号
        answer.setId(Long.valueOf(id));
        int i = answerService.addStudyAnswer(answer,num);
        String createTime = answerService.getCreateTime (Long.valueOf (id));
        answer.setCreateTime (Timestamp.valueOf (createTime));
        if (i == 1){
            return new Result (Code.POST_OK,answer,"创建回复消息成功!");
        }else {
            return new Result (Code.POST_ERR,"创建回复消息失败!");
        }
    }
    @GetMapping("/{idlist}")
    public Result getfistcommentsByPostId(@PathVariable String idlist){
        List list = answerService.getfistcommentsByPostId (idlist);
        if(list.size () > 0){
            return new Result(Code.GET_OK,list,"获取成功!");
        }
        return new Result(Code.GET_ERR,"获取失败!");
    }

    /**
     * 删除单个回复
     * @return
     */
    @DeleteMapping("/byid/{id}")
    public Result deleteStudyAnswerById(@PathVariable Long id){
        System.out.println ("id是："+id);
        int i = answerService.deleteStudyAnswer (id);
        if (i == 1){
            return new Result(Code.DELETE_OK,"删除成功");
        }
        return new Result(Code.DELETE_ERR,"删除失败");
    }
    @DeleteMapping("/byarray/{answerIdlist}/{id}")
    public Result deleteStudyAnswerByArray(@PathVariable String answerIdlist ,@PathVariable Long id){
        String[] answerlist = answerIdlist.split (",");
        int i = answerService.deleteAnswerArray (answerlist, id);
        if(i > 0){
            return new Result (Code.DELETE_OK,"删除成功");
        }else{
            return new Result (Code.DELETE_ERR,"删除失败");
        }
    }
}
